package com.example.tencentimdemo.im

import android.app.Application
import android.util.Log
import com.tencent.imsdk.v2.*

/**
 * IM 工具类
 */
object ImUtils {
    private val TAG = javaClass.name
    val imManager: V2TIMManager = V2TIMManager.getInstance()
    private val sdkListener by lazy { ImSdkListener() }

    /** 初始化IM */
    fun initImSdk(context: Application){
        //IM日志配置
        val config = V2TIMSDKConfig().apply {
            logLevel = V2TIMSDKConfig.V2TIM_LOG_INFO
            logListener = object : V2TIMLogListener() {
                override fun onLog(logLevel: Int, logContent: String?) {
                    super.onLog(logLevel, logContent)
                }
            }
        }
        //SDK基本事件监听
        imManager.addIMSDKListener(sdkListener)
        //初始化SDK，连接服务器
        imManager.initSDK(context, ImGenerateTestUserSig.SDKAPPID, config)
    }


    /** 登录IM */
    fun loginIm(userId: String){
        imManager.login(userId,ImGenerateTestUserSig.genTestUserSig(userId),object : V2TIMCallback{
            override fun onSuccess() {
                Log.e(TAG,"登录成功")
            }
            override fun onError(p0: Int, p1: String?) {
                Log.e(TAG,"登录失败  code = $p0  , reason = $p1")
            }
        })
    }

    /** 获取登录用户 */
    fun getLoginUser(): String{
       return imManager.loginUser
    }

    /** 获取登录状态 */
    fun getLoginStatus(): Int{
        return imManager.loginStatus
    }

    /** 登出 */
    fun imLoginOut(){
        imManager.logout(object : V2TIMCallback{
            override fun onSuccess() {
                Log.e(TAG,"登出成功")
            }

            override fun onError(p0: Int, p1: String?) {
                Log.e(TAG,"登出失败  code = $p0  , reason = $p1")
            }

        })
    }








    /** im反初始化 */
    fun unInitImSdk(){
        imManager.removeIMSDKListener(sdkListener)
        imManager.unInitSDK()
    }

}